import React, {useEffect, useState} from 'react';
import {View, StyleSheet, ActivityIndicator} from 'react-native';
import {WebView} from 'react-native-webview';
import {useNavigation, type StaticScreenProps} from '@react-navigation/native';
import {useAppTheme} from 'tsun-smart-ui';

type Props = StaticScreenProps<{
  title: string;
  url: string;
}>;
const WebViewPage: React.FC<Props> = ({route}) => {
  const {title, url} = route.params;
  const theme = useAppTheme();
  const [loading, setLoading] = useState(true);
  const navigation = useNavigation();

  useEffect(() => {
    navigation.setOptions({
      headerTitle: title,
    });
  }, [title]);

  return (
    <View className="flex-1">
      {loading && (
        <View style={styles.loadingContainer}>
          <ActivityIndicator
            size="large"
            color={theme.colors?.brand?.primary}
          />
        </View>
      )}

      <WebView
        source={{uri: url}}
        style={styles.webView}
        onLoadStart={() => setLoading(true)}
        onLoadEnd={() => setLoading(false)}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  webViewContainer: {
    flex: 1,
  },
  webView: {
    flex: 1,
  },
  loadingContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 1,
  },
});

export default WebViewPage;
